package org.overmind.ieat.server.logic.provider;

import org.overmind.ieat.server.dao.provider.ProviderDao;
import org.overmind.ieat.server.entity.Provider;
import org.overmind.ieat.server.exceptions.provider.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author eugene.karanda
 */
@Service
public class ProviderManagerImpl implements ProviderManager {

    @Autowired
    private ProviderDao providerDao;

    @Override
    public List<Provider> getProviderList() {
        return providerDao.getProviderList();
    }

    @Override
    public Provider findById(int id) throws ProviderFindException {
        try {
            Provider provider = providerDao.findById(id);

            if (provider == null) {
                throw new ProviderFindException(id);
            }

            return provider;
        } catch (Exception exception) {
            throw new ProviderFindException(exception, id);
        }
    }

    @Override
    public boolean deleteById(int id) throws ProviderDeleteException {
        try {
            boolean result = providerDao.deleteById(id);

            if(!result) {
                throw new ProviderDeleteException(id);
            }

            return result;
        } catch (Exception exception) {
            throw new ProviderDeleteException(exception, id);
        }
    }

    @Override
    public Integer save(Provider provider) throws ProviderSaveException {
        try {
            Integer generatedId = providerDao.save(provider);

            if(generatedId == null) {
                throw new ProviderSaveException(provider);
            }

            return generatedId;
        } catch (Exception exception) {
            throw new ProviderSaveException(exception, provider);
        }
    }

    @Override
    public Provider update(int id, Provider provider) throws ProviderUpdateException {
        try {
            Provider updatedProvider = providerDao.update(id, provider);

            if(updatedProvider == null) {
                throw new ProviderUpdateException(id,  provider);
            }

            return updatedProvider;
        } catch (Exception exception) {
            throw new ProviderUpdateException(exception, id, provider);
        }
    }
}
